<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="模型编码" prop="datasetCode">
        <el-input
          v-model="queryParams.datasetCode"
          placeholder="请输入模型编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模型名称" prop="datasetName">
        <el-input
          v-model="queryParams.datasetName"
          placeholder="请输入模型名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模型用途" prop="datasetUsage">
        <el-select v-model="queryParams.datasetUsage" placeholder="请选择模型用途" clearable>
          <el-option
            v-for="dict in dict.type.data_dataset_usage"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数据源名称" prop="datasourceId">
        <el-select v-model="queryParams.datasourceId" placeholder="请选择数据源">
              <el-option
                v-for="datasource in datasourceList"
                :key="datasource.datasourceId"
                :label="datasource.datasourceName"
                :value="datasource.datasourceId">
              </el-option>
            </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['data:dataset:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['data:dataset:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['data:dataset:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="datasetList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键id" align="center" prop="datasetId" /> -->
      <el-table-column label="模型编码" align="center" prop="datasetCode" />
      <el-table-column label="模型名称" align="center" prop="datasetName" />
      <el-table-column label="模型用途" align="center" prop="datasetUsage">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.data_dataset_usage" :value="scope.row.datasetUsage"/>
        </template>
      </el-table-column>
      <el-table-column label="数据源" align="center" prop="datasourceId">
        <!-- 从datasourceList翻译 -->
        <template slot-scope="scope">  
          <!-- 使用作用域插槽渲染内容 -->  
          <span>  
            {{ getDatasourceName(scope.row) }}  
          </span>  
        </template> 
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['data:dataset:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['data:dataset:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handlePreview(scope.row)"
          >预览</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据集对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模型编码" prop="datasetCode">
          <el-input v-model="form.datasetCode" placeholder="请输入模型编码" />
        </el-form-item>
        <el-form-item label="模型名称" prop="datasetName">
          <el-input v-model="form.datasetName" placeholder="请输入模型名称" />
        </el-form-item>
        <div style="display: flex; flex-direction: row;">
          <el-form-item label="模型用途" prop="datasetUsage">
            <el-select v-model="form.datasetUsage" placeholder="请选择模型用途">
              <el-option
                v-for="dict in dict.type.data_dataset_usage"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="数据源" prop="datasourceId">
            <el-select v-model="form.datasourceId" placeholder="请选择数据源">
              <el-option
                v-for="datasource in datasourceList"
                :key="datasource.datasourceId"
                :label="datasource.datasourceName"
                :value="datasource.datasourceId">
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="模型配置" prop="datasetConfig">
          <el-input v-model="form.datasetConfig" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-divider content-position="center">数据集参数信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddDataDatasetParams">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteDataDatasetParams">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="dataDatasetParamsList" :row-class-name="rowDataDatasetParamsIndex" @selection-change="handleDataDatasetParamsSelectionChange" ref="dataDatasetParams">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="类型" prop="type" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.type" placeholder="请选择类型">
                <el-option
                  v-for="dict in dict.type.data_set_param_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="参数名" prop="name" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.name" placeholder="请输入参数名" />
            </template>
          </el-table-column>
          <el-table-column label="默认值" prop="defaultValue" width="160">
            <template slot-scope="scope">
              <el-input v-model="scope.row.defaultValue" placeholder="请输入默认值" />
            </template>
          </el-table-column>
          <el-table-column label="参数描述" prop="descript" width="250">
            <template slot-scope="scope">
              <el-input v-model="scope.row.descript" placeholder="请输入参数描述" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 预览弹出框 -->
    <el-dialog :visible.sync="previewDialogVisible" title="预览数据" width="80%">
      <el-table v-if="previewData && previewData.data && previewData.data.length > 0" 
        :data="previewData.data"
        :stripe="true"
        max-height="500px"
        >
        <el-table-column v-for="column in previewData.columns" 
        :key="column" 
        :prop="column" 
        :label="column"
        :min-width="150"
        >
        </el-table-column>
      </el-table>
      <div v-else>暂无数据</div>
      <!-- 分页器 -->
      <!-- <pagination
      v-show="previewData.total>0"
      :total="previewData.total"
      :page.sync="dataSetPreviewVo.pageNum"
      :limit.sync="dataSetPreviewVo.pageSize"
      @pagination="handlePreviewPagination"
    /> -->
    </el-dialog>
  </div>
</template>

<script>
import { listDataset, getDataset, delDataset, addDataset, updateDataset ,previewDataset} from "@/api/data/dataset";
import { listDatasource} from "@/api/data/datasource";

export default {
  name: "Dataset",
  dicts: ['data_set_param_type', 'data_dataset_usage'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedDataDatasetParams: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据集表格数据
      datasetList: [],
      // 数据集参数表格数据
      dataDatasetParamsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        datasetCode: null,
        datasetName: null,
        datasetUsage: null,
        datasourceId: null,
      },
      dataSetPreviewVo: {
        datasetId: null,
        datasetCode: null,
        // pageNum: 1,
        // pageSize: 10
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        datasetCode: [
          { required: true, message: "模型编码不能为空", trigger: "blur" }
        ],
        datasetName: [
          { required: true, message: "模型名称不能为空", trigger: "blur" }
        ],
        datasetUsage: [
          { required: true, message: "模型用途不能为空", trigger: "change" }
        ],
        datasetConfig: [
          { required: true, message: "模型配置不能为空", trigger: "blur" }
        ],
        datasourceId: [
          { required: true, message: "数据源id不能为空", trigger: "blur" }
        ],
      },
      // 预览弹窗显示控制
      previewDialogVisible: false,
      // 预览数据
      previewData: {
      },
      // 数据源列表
      datasourceList: [],
    };
  },
  created() {
    this.getDatasourceList();
    this.getList();
  },
  methods: {
    /** 查询数据集列表 */
    getList() {
      this.loading = true;
      listDataset(this.queryParams).then(response => {
        this.datasetList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 查询数据源列表
    getDatasourceList(){
      listDatasource().then(response => {
        this.datasourceList = response.rows;
      });
    },
    getDatasourceName(row){
      const datasourceId = row.datasourceId;
      const datasource = this.datasourceList.find(datasource => datasource.datasourceId === datasourceId);  
      return datasource ? datasource.datasourceName : '未知'; 
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        datasetId: null,
        datasetCode: null,
        datasetName: null,
        datasetUsage: null,
        datasetConfig: null,
        datasourceId: null,
        createId: null,
        createTime: null,
        updateId: null,
        updateTime: null
      };
      this.dataDatasetParamsList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.datasetId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加数据集";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      if (row.datasetId) {
        this.form = row;
        this.dataDatasetParamsList = row.dataDatasetParamsList;
      }
      const datasetId = row.datasetId || this.ids
      getDataset(datasetId).then(response => {
        this.form = response.data;
        this.dataDatasetParamsList = response.data.dataDatasetParamsList;
        this.open = true;
        this.title = "修改数据集";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.dataDatasetParamsList = this.dataDatasetParamsList;
          if (this.form.datasetId != null) {
            updateDataset(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDataset(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const datasetIds = row.datasetId || this.ids;
      this.$modal.confirm('是否确认删除数据集编号为"' + datasetIds + '"的数据项？').then(function() {
        return delDataset(datasetIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 数据集参数序号 */
    rowDataDatasetParamsIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 数据集参数添加按钮操作 */
    handleAddDataDatasetParams() {
      let obj = {};
      obj.name = "";
      obj.descript = "";
      obj.defaultValue = "";
      obj.type = "";
      this.dataDatasetParamsList.push(obj);
    },
    /** 数据集参数删除按钮操作 */
    handleDeleteDataDatasetParams() {
      if (this.checkedDataDatasetParams.length == 0) {
        this.$modal.msgError("请先选择要删除的数据集参数数据");
      } else {
        const dataDatasetParamsList = this.dataDatasetParamsList;
        const checkedDataDatasetParams = this.checkedDataDatasetParams;
        this.dataDatasetParamsList = dataDatasetParamsList.filter(function(item) {
          return checkedDataDatasetParams.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleDataDatasetParamsSelectionChange(selection) {
      this.checkedDataDatasetParams = selection.map(item => item.index)
    },
    /** 数据集预览按钮操作 */
    handlePreview(row) {
      this.dataSetPreviewVo.datasetId = row.datasetId;
      previewDataset(this.dataSetPreviewVo).then(response => {
        if (response.code === 200) {
            this.previewData = response.data;
            this.previewDialogVisible = true; // 显示预览弹窗
          } else {
            this.$message.error(response.msg);
          }
      }).catch(error => {
          this.$message.error("预览接口请求失败");
      });;
    },
    /** 处理预览分页器变化 */
    handlePreviewPagination(page, limit) {
      this.dataSetPreviewVo.pageNum = page;
      this.dataSetPreviewVo.pageSize = limit;
      // 在这里调用 handlePreview 方法，并传递参数
      this.handlePreview(this.dataSetPreviewVo.datasetId);
    }, 
    /** 获取数据源列表 */
    getDatasourceList() {
      listDatasource().then(response => {
        this.datasourceList = response.rows;
      });
    },
  }
};
</script>
